package com.itbac.config.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.itbac.domain.ResponseData;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * sentinel 自定义异常处理页面
 */
@Component
public class ExceptionHandlerPage implements UrlBlockHandler {
    /**
     * BlockException 异常接口，包含Sentinel的5个异常实现类
     * 1.FlowException  限流异常
     * 2.DegradeException 降级异常
     * 3.ParamFlowException 热点规则，参数限流异常
     * 4.AuthorityException 授权异常，黑白名单
     * 5.SystemBlockException 系统负载异常
     */
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        //设置响应类型
        response.setContentType("application/json;charset=utf-8");
        ResponseData data = null;

        if (e instanceof FlowException){
            data = new ResponseData(-1, null, "限流异常");
        }else if (e instanceof DegradeException){
            data = new ResponseData(-2, null, "降级异常");
        }else if (e instanceof ParamFlowException){
            data = new ResponseData(-3, null, "参数限流异常");
        }else if (e instanceof AuthorityException){
            data = new ResponseData(-4, null, "黑白名单异常");
        }else if (e instanceof SystemBlockException){
            data = new ResponseData(-5, null, "系统负载异常");
        }
        response.getWriter().write(JSON.toJSONString(data));
    }
}
